package com.example.springbootconfig.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.ResourceBundle;

//@Configuration
public class DbConfig {



    /**
     * 方法一, 使用Environment读取properties参数
     * 参数必须在application.properties中
     * @return
     */
    @Autowired
    private Environment env;

    @Bean
    @Primary
    public void getDataSource1() {
        System.out.println("env.getProperty(\"jdbc.user\")");

    }


    /**
     * 方法二, 使用注解自动读取
     * 参数可以在指定的文件中
     */
    @Autowired
    private DbConfigProperties dbConfigProperties;
    /*
    @Bean
    @Primary
    */
    public DataSource getDataSource2() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(dbConfigProperties.getUser());
        dataSource.setPassword(dbConfigProperties.getPassword());
        dataSource.setUrl(dbConfigProperties.getUrl());
        dataSource.setDriverClassName(dbConfigProperties.getDriver());

        return dataSource;
    }

    /**
     * 方法三, 使用@Value注解, 让spring自动注入
     * 参数必须写在application.properties中
     * `@Value`注解的Target是Field, Method, Parameter, Annotation
     */
    /*
    @Bean
    @Primary
    */
    public DataSource getDataSource3(@Value("${jdbc.user}") String user,
                                     @Value("${jdbc.password}") String password,
                                     @Value("${jdbc.driver}") String driver,
                                     @Value("${jdbc.url}") String url) {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driver);
        dataSource.setUrl(url);

        return dataSource;
    }

    /**
     * 方法四: 最原始的方法, 用Bundle, 可以读取任何properties
     */
    /*
    @Bean
    @Primary
    */
    public DataSource getDataSource4() throws IOException {
        // Bundle 使用方法一

        /*
        ResourceBundle bundle
                = new PropertyResourceBundle(getClass().getClassLoader().getResourceAsStream("db.properties"));
        */

        // Bundle 方法二
        ResourceBundle bundle = ResourceBundle.getBundle("db");

        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUsername(bundle.getString("jdbc.user"));
        dataSource.setPassword(bundle.getString("jdbc.password"));
        dataSource.setUrl(bundle.getString("jdbc.url"));
        dataSource.setDriverClassName(bundle.getString("jdbc.driver"));

        return dataSource;
    }
}
